<?php
/** 命名空间 */
namespace app\cp_outfile;

/**
 * Hosts文件
 */

function hosts(\ounun\Mysql $db)
{
	$rs      = $db->dataArray('SELECT * FROM  `hyapi_idc_hosts_domain` ');
	$hosts   = array();
	foreach ($rs as $v)
	{
		$ip 					= str_pad($v['ip'], 32);
		$hosts[$v['domain']] 	= "{$ip} {$v['domain']}";
	}
	ksort($hosts);
	$hosts  	= implode("\n", 	$hosts);
	//
	$home_rs	= $db->dataArray('SELECT `home_id`,`home_key` FROM  `hyapi_idc_home` ');
	$home_list	= array();
	foreach ($home_rs as $v)
	{
		$home_list[$v['home_id']] = $v['home_key'];
	}
	$host_rs		= $db->dataArray('SELECT `home_id`,`default_ip`,`ct_ip`,`cu_ip`,`cm_ip`,`side_ip`,`domains` FROM `hyapi_idc_hosts` ');
	$host_list		= array();
	foreach($host_rs as $v)
	{
		$domains 	= explode(',',$v['domains']);
		foreach($domains as $v2){
			$v2 	= trim($v2);
			if($v2)
			{
				$host_list[$v['home_id']][$v2] = array(
						'default_ip'=>str_pad($v[$v['default_ip']],	32),
						'side_ip'	=>str_pad($v['side_ip'], 		32)
				);
			}
		}
	}
	foreach ($host_list as $k=>$v)
	{
		$filename		= "hosts_{$home_list[$k]}";
		$filecontent	= "# {$home_list[$k]} [side]\n";
		foreach ($v as $domain => $ips)
		{
			$filecontent	.= "{$ips['side_ip']} {$domain}\n";
		}
	
		foreach ($host_list as $home_id => $host)
		{
			if($home_id != $k)
			{
				$filecontent	.= "\n# {$home_list[$home_id]}\n";
				foreach ($host as $domain => $ips)
				{
					$filecontent	.= "{$ips['default_ip']} {$domain}\n";
				}
			}
		}
		$filecontent = $filecontent."\n# HostsDomain\n".$hosts;
		// ---  输出 --- //
		file_put_contents(Const_Dir_Out.'php_hosts/host/'.$filename,$filecontent);
	}
}


/**
 * 配制文件
 */
function config_php(\ounun\Mysql $db)
{
	// config.global.php 
	$filename_global			= Const_Dir_Out.'php_config_php/config.global.php';
	$contents_global  			= file_get_contents($filename_global);
	// config.serv.c*.s*.php
	$filename_php_source		= Const_Dir_Out.'php_config_php/template.config.php.txt';
	$contents_php_source		= file_get_contents($filename_php_source);
	// config.serv.c*.s*.php
	$filename_yrl_source		= Const_Dir_Out.'php_config_yrl/template.config.yrl.txt';
	$contents_yrl_source		= file_get_contents($filename_yrl_source);
	// template.start.txt
	$filename_start_start_source	= Const_Dir_Out.'php_start/template.start.txt';
	$contents_start_start_source	= file_get_contents($filename_start_start_source);
	// template.master.txt
	$filename_start_master_source	= Const_Dir_Out.'php_start/template.master.txt';
	$contents_start_master_source	= file_get_contents($filename_start_master_source);
	// template.stop.txt
	$filename_start_stop_source		= Const_Dir_Out.'php_start/template.stop.txt';
	$contents_start_stop_source		= file_get_contents($filename_start_stop_source);
	
	
	// hyapi_idc_hosts
	$rs 						= $db->dataArray('SELECT * FROM  `hyapi_idc_hosts` ');
	$idc_hosts					= array();
	foreach ($rs as $v)
	{
		$v['domains'] 	= explode(',',$v['domains']);
		$domains		= array();
		foreach($v['domains'] as $v2)
		{
			$v2 	= trim($v2);
			if($v2)
			{
				array_push($domains, $v2);
			}
		}
		
		$v['domains']			  = $domains;
		$idc_hosts[$v['host_id']] = $v;
	}
	// hyapi_idc_fun
	$rs 						= $db->dataArray('SELECT * FROM  `hyapi_idc_fun` ');
	$idc_fun					= array();
	foreach ($rs as $v)
	{
		if('2' == $v['type'] && $v['exts'])
		{
			$exts   = unserialize($v['exts']);
			if ($exts)
			{
				$v['user'] 	 	= $exts['user'];
				$v['passwd']  	= $exts['passwd'];
				$v['port']  	= $exts['port'];
			}
		}
		$idc_fun[$v['fun_id']]	= $v;
	}
	// hyapi_serv
	$rs 						= $db->dataArray('SELECT * FROM  `hyapi_serv` ');
	$serv						= array();	
	foreach ($rs as $v)
	{
		if($v['merge_target'])
		{
			$serv[$v['merge_target']]['merge'][$v['sid']] = $v['sid'];
		}
		$v['work_day']			= str_replace('-', ',',$v['work_day']);
		$serv[$v['sid']]		= $v;
	}
	// hyapi_serv_ver
	$rs 						= $db->dataArray('SELECT * FROM  `hyapi_serv_ver` ');
	$ver						= array();
	foreach ($rs as $v)
	{
		$ver[$v['ver_id']]		= $v;
	}	
	// hyapi_coop_area
	$rs 						= $db->dataArray('SELECT * FROM  `hyapi_coop_area` ');
	$areas						= array();
	foreach ($rs as $v)
	{
		$areas[$v['cid']][$v['area_id']]	= $v;
	}
	// hyapi_coop
	$rs 						= $db->dataArray('SELECT * FROM  `hyapi_coop` ');
	$coops						= array();
	$global_data_cid			= '';
	foreach ($rs as $v)
	{
		$coops[$v['cid']]		=  $v;
		if(!$v['cf_url_site'])
		{
			$v['cf_url_site']	= $GLOBALS['scfg']['coop_list'][0]['site'];
		}
		$global_data_cid  	   .= "\t'{$v['cid']}'	=> array('site'=>'{$v['cf_url_site']}'),\n";
	}
	$contents_global			= private_file_contents_replace($contents_global,$global_data_cid,'cid',"\t");
	// hyapi_serv_coop
	$rs 						= $db->dataArray('SELECT * FROM  `hyapi_serv_coop` where `sid` > 0 ');
	$start_data					= array();
	$global_data_domain			= '';
	foreach ($rs as $v)
	{
		$domains	= \app\hy\var_replace($v['domains'], $v['sid'], $v['csid'], $v['area_id'],'', '');
		$domains 	= explode(',',$domains);
		$domains2	= array();
		foreach($domains as $v2)
		{
			$v2 	= trim($v2);
			if($v2)
			{
				array_push($domains2, $v2);
				$global_data_domain   .= "\t'{$v2}'	=> array('cid'=>{$v['cid']}, 'sid'=> {$v['sid']} ),\n";
			}
		}	
		$data	= array(
				'sid'		=> $v['sid'],
				'csid'		=> $v['csid'],
				'cid'		=> $v['cid'],
				'coop_name' 		=> $coops[$v['cid']]['cname'],
				'coop_game_name' 	=> $coops[$v['cid']]['cf_gname'],
				'coop_serv_name'    => $v['serv_name'],
				'key'				=> $coops[$v['cid']]['ckey'],
		
				'cs'			=> array(
						'tel' 		=> $coops[$v['cid']]['cf_cs_tel'],
						'email' 	=> $coops[$v['cid']]['cf_cs_email'],
				),
				'url'			=> array(
						'site'		=> $coops[$v['cid']]['cf_url_site'],
						'login'		=> $coops[$v['cid']]['cf_url_login'],
						'bbs'		=> $coops[$v['cid']]['cf_url_bbs'],
						'pay'		=> $coops[$v['cid']]['cf_url_pay'],
						'help'		=> $coops[$v['cid']]['cf_url_help'],
						'fcm'		=> $coops[$v['cid']]['cf_url_fcm'],
				),
				'fav'			=> array(
						'url'		=> $coops[$v['cid']]['cf_url_fcm'],
						'title'		=> $coops[$v['cid']]['cf_fav_title'],
				),
				'ver_serv'		=> $ver[ $serv[$v['sid']]['ver_id'] ]['ver_serv'],
				'ver_res'		=> $ver[ $serv[$v['sid']]['ver_id'] ]['ver_res'],
				'ver_game'		=> $ver[ $serv[$v['sid']]['ver_id'] ]['ver_game'],
				'ver_ui'		=> $ver[ $serv[$v['sid']]['ver_id'] ]['ver_ui'],
				'ver_data'		=> $ver[ $serv[$v['sid']]['ver_id'] ]['ver_data'],
		
				'stat'			=> $areas[$v['cid']][$v['area_id']]['stat']?"http://{$domains2[0]}/Progress.html":'',
				'create'		=> array(
						'enable'	=> $areas[$v['cid']][$v['area_id']]['create_enable'],
						'rmb'		=> $areas[$v['cid']][$v['area_id']]['create_rmb'],
						'point'		=> $areas[$v['cid']][$v['area_id']]['create_point'],
				),
				'login'			=> array(
						'enable'	=> $areas[$v['cid']][$v['area_id']]['login_enable'],
						'reset'		=> $areas[$v['cid']][$v['area_id']]['login_reset'],
						'rmb'		=> $areas[$v['cid']][$v['area_id']]['login_rmb'],
						'point'		=> $areas[$v['cid']][$v['area_id']]['login_point'],
				),
		
				'domain'		=> $domains2[0],				
		
				'socket_host'	=> $idc_hosts[  $idc_fun[ $serv[$v['sid']]['host_id_game']  ]['host_id']  ]['domains'][0],
				'socket_port'	=> $serv[$v['sid']]['port'],
		
				'mysql'			=> array(
						'host' => $idc_hosts[  $idc_fun[ $serv[$v['sid']]['host_id_mysql']  ]['host_id']  ]['domains'][0],
						'port' => $idc_fun[ $serv[$v['sid']]['host_id_mysql']  ]['port'],
						'user' 	 => $idc_fun[ $serv[$v['sid']]['host_id_mysql']  ]['user'],
						'passwd' => $idc_fun[ $serv[$v['sid']]['host_id_mysql']  ]['passwd'],
				),
				
				// yrl   ===================================================
				'sid_merge'		=> $serv[$v['sid']]['merge']? implode(',', $serv[$v['sid']]['merge']):'',
				'business'		=> $serv[$v['sid']]['business'],
				'level_max'		=> $serv[$v['sid']]['level_max'],
				'key_private'	=> Const_Key_Conn_Private,
				'work_day'		=> $serv[$v['sid']]['work_day'],
				'mongo'			=> array(
						// 暂时 用MYSQL  port写死 27017
						'host'  => $idc_hosts[  $idc_fun[ $serv[$v['sid']]['host_id_mysql']  ]['host_id']  ]['domains'][0],
						'port'	=> 27017
				),
				//        ===================================================
		);
		// config.serv.c{$v['cid']}.s{$v['sid']}.php
		$filename_php_out		= Const_Dir_Out."php_config_php/config.serv.c{$v['cid']}.s{$v['sid']}.php";	
		$contents_php_out		= private_file_var_replace($contents_php_source, $data);
		file_put_contents($filename_php_out,$contents_php_out);
		// 被合服的 不生成
		$filename_yrl_out		= Const_Dir_Out."php_config_yrl/ini.all.config.{$v['sid']}.yrl";
		if($serv[$v['sid']]['merge_target'] == '0')
		{
			// 开始数据
			$start_data[ $serv[$v['sid']]['host_id_game'] ][$v['sid']]	  = $serv[$v['sid']];
			// ini.all.config.{$v['sid']}.yrl			
			$contents_yrl_out		= private_file_var_replace($contents_yrl_source, $data);
			file_put_contents($filename_yrl_out,$contents_yrl_out);
		}else {
			@unlink($filename_yrl_out);
		}
	}
	$contents_global		= private_file_contents_replace($contents_global,$global_data_domain,'domain',"\t");
	file_put_contents($filename_global,$contents_global);
	// 启动 与 停服项  ---------------------------------------------------------------
	// template.start.txt
	// $filename_start_start_source	= Const_Dir_Out.'php_start/template.start.txt';
	// $contents_start_start_source	= file_get_contents($filename_start_start_source);
	// template.master.txt
	// $filename_start_master_source	= Const_Dir_Out.'php_start/template.master.txt';
	// $contents_start_master_source	= file_get_contents($filename_yrl_source);
	// template.stop.txt
	// $filename_start_stop_source		= Const_Dir_Out.'php_start/template.stop.txt';
	// $contents_start_stop_source		= file_get_contents($filename_start_stop_source);
	$cookie  = 'c'.substr(md5('yxdo'),4,9);
	foreach ($start_data as $fun_id => $lists)
	{
		$domain  	= $idc_hosts[  $idc_fun[$fun_id]['host_id']  ]['domains'][0];
		$ct_ip		= $idc_hosts[  $idc_fun[$fun_id]['host_id']  ]['ct_ip'];
		
		$filename_start_start_out		= Const_Dir_Out.'php_start/host/start_'.$ct_ip.'.sh';
		$filename_start_stop_out		= Const_Dir_Out.'php_start/host/stop_'.$ct_ip.'.sh';
		$contents_start_start_out		= '';
		foreach ($lists as $sid=>$v)
		{
			$data							= array(
					'cookie'	=> $cookie,		
					'domain'	=> $domain,
					'ver_serv'	=> $ver[ $v['ver_id'] ]['ver_serv'],
					'sid'		=> $v['sid'],
					'detached'	=> '-detached',
					'type'		=> '',
			);			
			$contents_start_start_out  .= private_file_var_replace($contents_start_start_source, $data);
			/////////////////////////////////////////////////////////////////////////////////////////////
			$filename_start_serv_out	= Const_Dir_Out.'php_start/serv/start_'.$sid.'_'.$ct_ip.'.sh';
			$data						= array(
					'cookie'	=> $cookie,		
					'domain'	=> $domain,
					'ver_serv'	=> $ver[ $v['ver_id'] ]['ver_serv'],
					'sid'		=> $v['sid'],
					'detached'	=> '',
					'type'		=> '# ',
			);
			$contents_start_serv_out	= private_file_var_replace($contents_start_start_source, $data);
			file_put_contents($filename_start_serv_out,$contents_start_serv_out);
		}
		$data							= array(
				'cookie'	=> $cookie,		
				'domain'	=> $domain,
				'detached'	=> '-detached',
				'serv_list' => $contents_start_start_out
		);
		$contents_start_start_out       = private_file_var_replace($contents_start_master_source, 	$data);
		$contents_start_stop_out		= private_file_var_replace($contents_start_stop_source, 	$data);		
		//
		file_put_contents($filename_start_start_out,$contents_start_start_out);
		file_put_contents($filename_start_stop_out, $contents_start_stop_out);		
	}
	//调用svndataup脚本更新
	\app\cp_outfile\call_svndateup();
	//print_r($data_start);
	//exit();
}
/**
 * 生成Sersync服务器的IP源
 */
function ause(\ounun\Mysql $db)
{
	$host_rs	= $db->dataArray('SELECT `host_id`,`default_ip`,`ct_ip`,`cu_ip`,`cm_ip`,`side_ip` FROM `hyapi_idc_hosts` ');
	$host_list	= array();
	foreach($host_rs as $v)
	{
		$host_list[$v['host_id']]		= $v;
		$host_list[$v['host_id']][ip]	= str_pad($v[$v['default_ip']],	32);
	}
	$fun_rs		= $db->dataArray('SELECT `fun_id`,`host_id`,`type` FROM `hyapi_idc_fun` ');
	$fun_list	= array();
	foreach ($fun_rs as $v)
	{
		$fun_list[$v['fun_id']]			= $v;
		$fun_list[$v['fun_id']][ip]		= $host_list[$v['host_id']][ip];
	}
	$filename='data.txt';
	$filecontent = '';
	foreach ($fun_list as $k=>$v)
	{
		$filecontent .= "{$v['ip']}{$v['type']}\n";

	} 
	file_put_contents(Const_Dir_Out.'php_hosts/autose/data/'.$filename,$filecontent);
	//调用svndataup脚本更新
	\app\cp_outfile\call_svndateup();	
}
/**
 * 文件内容 替换
 */
function private_file_contents_replace($contents,$data,$tag,$tab="\t\t\t")
{
	$auto_code 	 = "/*** AUTO CODE BEGIN({$tag}) *************** don't touch this line **********/\n";
	$auto_code 	.= "{$tab}/** =============================== 自动生成的代码 =============================== **/\n";
	$auto_code 	.= $data;
	$auto_code 	.= "{$tab}/** =============================== 自动生成的代码 =============================== **/\n";
	$auto_code 	.= "{$tab}/***************** don't touch this line *********** AUTO CODE END({$tag}) ***/";
	return preg_replace('/\/\*\*\* AUTO CODE BEGIN\('.$tag.'\) [\s\S]*AUTO CODE END\('.$tag.'\) \*\*\*\//m',$auto_code,$contents);
}
/**
 * 文件Yrl 替换
 */
function private_file_var_replace($contents,$data)
{
	extract($data);
	return preg_replace('/\{(\$.*?)\}/e', "$1", $contents);
}
/**
 * 调用svndataup脚本
 */
function call_svndateup()
{
	if (\file_exists(Const_Dir_Out.'php_hosts/svnup/svndateup.sh'))
	{
		exec("/bin/bash '".Const_Dir_Out."php_hosts/svnup/svndateup.sh'",$arr,$status);
	}
}
